package icu.yougan.trade.service.Impl;

import icu.yougan.trade.entity.User;
import icu.yougan.trade.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService; // 你的原始用户服务

    @Override
    public UserDetails loadUserByUsername(String accountNumber) throws UsernameNotFoundException {
        // 重要：根据你的业务查询用户
        User user = userService.getUserByAccountNum(accountNumber);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + accountNumber);
        }
        // 检查账户状态（1表示封禁）
        if (user.getUserStatus()!=null&&user.getUserStatus() == 1) {
            throw new LockedException("账户已被封禁");
        }
        if(user.getUserStatus()==null)
        {
            Byte b=0;
            user.setUserStatus(b);
        }

        // 构建Spring Security用户对象
        return new org.springframework.security.core.userdetails.User(
                user.getAccountNumber(),
                user.getUserPassword(),
                getAuthorities(user.getUserStatus())
        );
    }

    // 授予权限（根据业务需求调整）
    private Collection<? extends GrantedAuthority> getAuthorities(Byte status) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 示例权限配置
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        if (status == 1) { // 假设2是管理员
            authorities.add(new SimpleGrantedAuthority("ROLE_BAN"));
        }
        return authorities;
    }
}